<!--
 * @name: **列表
 * @content: 
 * @Author: joyce
 * @Date: 2020-05-20 10:48:35
-->
<template>
  <div class="Box">
    <div class="titles">新增问卷</div>
    <el-switch
      v-model="form.anonymous"
      active-text="匿名发布"
      inactive-text="实名发布"
      style="margin:20px 0 0 0"
    >
    </el-switch>
    <el-form ref="form" :model="form">
      <el-form-item
        label="问卷标题"
        :rules="[{ required: true, message: '投票标题不能为空' }]"
      >
        <el-input v-model="form.title" placeholder="请输入问卷标题"></el-input>
      </el-form-item>
      <el-form-item
        label="问卷描述"
        :rules="[{ required: true, message: '投票描述不能为空' }]"
      >
        <el-input
          v-model="form.describe"
          placeholder="请输入问卷描述"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="截止时间"
        :rules="[{ required: true, message: '截止时间不能为空' }]"
      >
        <el-date-picker
          v-model="form.endtime"
          type="datetime"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否有图片">
        <el-switch v-model="isimages"></el-switch>
      </el-form-item>
      <el-form-item label="问卷图片" v-if="isimages">
        <div class="updataImg">
          <div class="delectBox" v-if="form.images != ''">
            <el-image
              style="width: 100px; height: 100px;margin-left:10px"
              :src="form.images"
            ></el-image>
            <i class="el-icon-delete icon" @click="deleItem('images', 0)"></i>
          </div>
          <div
            class="addImg"
            @click="upInput('images', 0)"
            v-if="form.images == ''"
          >
            +
          </div>
        </div>
      </el-form-item>
      <el-form-item label="是否有链接">
        <el-switch v-model="isvideo"></el-switch>
      </el-form-item>
      <el-form-item label="问卷链接" v-if="isvideo">
        <el-input v-model="form.videos" placeholder="请输入问卷链接"></el-input>
      </el-form-item>
      <el-form-item
        v-for="(item, index) in optionlist"
        :label="'选项' + (index + 1)"
        :key="item.key"
        class="for_css"
      >
        <el-form-item
          :label="'选项' + (index + 1) + '标题'"
          style="margin-bottom:20px"
          v-if="item.optiontype == 1"
        >
          <el-input
            v-model="item.optiontitle"
            :placeholder="'请输入选项' + (index + 1) + '标题'"
          ></el-input>
          <el-button
            @click.prevent="addsub1(index)"
            size="small"
            type="primary"
            plain
            >添加子选项</el-button
          >
        </el-form-item>
        <div
          class="dan"
          v-for="(item1, index1) in item.subopitons"
          :key="item1.key"
        >
          <div v-if="item.optiontype == 1">
            <el-form-item
              :label="'单选项' + (index1 + 1) + '标题'"
              style="margin-bottom:10px"
            >
              <el-input
                v-model="item1.subopitonstitile"
                :placeholder="'请输入单选项' + (index1 + 1) + '标题'"
              ></el-input>
              <el-button
                v-if="index1 != 0 || item.subopitons.length > 1"
                @click.prevent="removesub1(item1, index)"
                size="small"
                type="danger"
                plain
                style="float:right;margin:20px 0"
                icon="el-icon-delete"
              ></el-button>
            </el-form-item>
          </div>
        </div>
        <el-form-item
          :label="'选项' + (index + 1) + '标题'"
          style="margin-bottom:20px"
          v-if="item.optiontype == 2"
        >
          <el-input
            v-model="item.optiontitle"
            :placeholder="'请输入选项' + (index + 1) + '标题'"
            style="margin-bottom:5px"
          ></el-input>
          <!-- <el-input
            v-model.number="item.subopitonsitme"
            :placeholder="'请输入多选项' + (index + 1) + '选择次数'"
          ></el-input> -->
          <div>{{ "多选项" + (index + 1) + "  的选择次数" }}</div>
          <el-input-number
            v-model="item.subopitonsitme"
            controls-position="right"
            @change="handleChange"
            :min="1"
            :max="10"
          ></el-input-number>
          <el-button
            @click.prevent="addsub2(index)"
            size="small"
            type="primary"
            plain
            style="margin:10px"
            >添加子选项</el-button
          >
        </el-form-item>
        <div
          class="dan"
          v-for="(item1, index1) in item.mulopitons"
          :key="item1.key"
        >
          <div v-if="item.optiontype == 2">
            <el-form-item
              :label="'多选项' + (index1 + 1) + '标题'"
              style="margin-bottom:10px"
            >
              <el-input
                v-model="item1.subopitonstitile"
                :placeholder="'请输入多选项' + (index1 + 1) + '标题'"
              ></el-input>

              <el-button
                v-if="index1 != 0 || item.mulopitons.length > 1"
                @click.prevent="removesub2(item1, index)"
                size="small"
                type="danger"
                plain
                style="float:right;margin:20px 0"
                icon="el-icon-delete"
              ></el-button>
            </el-form-item>
          </div>
        </div>

        <el-form-item
          :label="'填空' + (index + 1) + '标题'"
          style="margin-bottom:20px"
          v-if="item.optiontype == 3"
        >
          <el-input
            v-model="item.optiontitle"
            :placeholder="'请输入填空' + (index + 1) + '标题'"
            style="margin-bottom:5px"
          ></el-input>
        </el-form-item>

        <el-form-item label-width="68px">
          <el-button
            v-if="index != 0 || optionlist.length > 1"
            @click.prevent="removeDomain(item)"
            size="small"
            type="danger"
            style="float:right;margin:20px 0"
            plain
            >删除选项</el-button
          >
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button @click="addDomain1" type="primary" plain
          >新增单选项</el-button
        >
        <el-button @click="addDomain2" type="primary" plain
          >新增多选项</el-button
        >
        <el-button @click="addDomain3" type="primary" plain>新增填空</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit"
          style="width:200px;float:right;margin:20px"
          >发布</el-button
        >
      </el-form-item>
      <input
        type="file"
        name="file"
        accept="image/*"
        id="upload"
        @change="upImgPath"
        ref="referenceUpload"
        style="opacity:0"
      />
    </el-form>
  </div>
</template>

<script>
import { UPQUESTION_IMG } from "@/api/questionpc";
export default {
  data() {
    return {
      form: {
        title: "",
        describe: "",
        endtime: "",
        images: "",
        videos: "",
        anonymous: false
      },
      optionlist: [
        // {
        //   optiontitle: "", //选项标题
        //   optiontype: 1, //选项类型
        //   subopitons: [
        //     {
        //       subopitonstitile: "", //子选项标题
        //       subopitonsnum: 0 //子选项被选择数
        //     }
        //   ] //子选项
        // }
      ],
      isoptionindex: 0,
      isimages: false,
      isvideo: false,
      labelPosition: "no",
      uploadImage: {
        //上传的图片
        images: "" //附加文件
      },
      imageList: {
        images: [] //附加文件
      }, //编辑时的图片检测（用于删除）
      deleImgArr: [], //要删除的文件
      selectImgArr: "", //选择的图片标签
      isedit: false
    };
  },
  created() {
    this.getdata();
  },
  methods: {
    getdata() {
      if (!this.$route.params.id) {
        this.isedit = true;
      }
    },
    //发布
    async onSubmit() {
      try {
        if (
          this.form.title != "" &&
          this.form.describe != "" &&
          this.form.endtime != ""
        ) {
          //判断是否完善必备信息
          var images = ""; //主图图片
          var datas = { option: [] }; //总上传数据
          datas["title"] = this.form.title;
          datas["describe"] = this.form.describe;
          datas["endtime"] = this.form.endtime;
          if (this.isimages) {
            if (this.form.images != "") {
              datas["images"] = this.form.images;
              images = this.uploadImage.images;
            } else {
              throw new Error("isimages");
            }
          }
          if (this.isvideo) {
            if (this.form.videos != "") {
              datas["videos"] = this.form.videos;
            } else {
              throw new Error("isvideo");
            }
          }
          this.optionlist.forEach(e => {
            if (e.optiontype == 1) {
              if (e.optiontitle != "") {
                datas["option"].push({
                  optiontitle: e.optiontitle,
                  subopitons: e.subopitons,
                  optiontype: e.optiontype
                });
              } else {
                throw new Error("optiontitleno");
              }
            } else if (e.optiontype == 2) {
              if ((e.optiontitle != "", e.subopitonsitme != null)) {
                datas["option"].push({
                  optiontitle: e.optiontitle,
                  optiontype: e.optiontype,
                  subopitonsitme: e.subopitonsitme,
                  mulopitons: e.mulopitons
                });
              } else {
                throw new Error("optiontitleno");
              }
            } else if (e.optiontype == 3) {
              if (e.optiontitle != "") {
                datas["option"].push({
                  optiontitle: e.optiontitle,
                  optiontype: e.optiontype
                });
              } else {
                throw new Error("optiontitleno");
              }
            } else {
              throw new Error("optiontitleno");
            }
          });

          console.log(datas);

          var formData = new FormData();
          if (this.isimages) {
            formData.append("images", images);
          }

          datas["Creat_people"] = this.$store.getters.userInfo._id;
          formData.append("formData", JSON.stringify(datas));
          var a = await UPQUESTION_IMG(formData);
          console.log(a);
          if (a.code == 200) {
            this.$message({
              type: "success",
              message: "发布成功"
            });
            this.$finish_taskdata(11, this.$store.getters.userInfo._id);
            this.$router.push({
              path: "/personalCenter", //跳转路径
              name: "personalCenter", //跳转路径的name值，不写跳转后页面取不到参数
              // 参数 兑换记录
              query: {
                work: 6
              }
            });
          } else {
            this.$message({
              type: "warning",
              message: "发布失败，网络出错"
            });
          }
        } else {
          this.$message({
            type: "warning",
            message: "必填信息未填写完善"
          });
        }
      } catch (e) {
        if (e.message == "optiontitleno") {
          this.$message({
            type: "warning",
            message: "选项未填完善，请填写选项"
          });
        }
        if (e.message == "isvideo") {
          this.$message({
            type: "info",
            message: "已选投票视频链接，但未填写"
          });
        }
        if (e.message == "isimages") {
          this.$message({
            type: "warning",
            message: "已选投票主图，但未上传图片"
          });
        }
      }
    },
    //图片处理
    upInput(item, index) {
      this.selectImgArr = item;
      console.log(index);
      this.isoptionindex = index;
      document.getElementById("upload").click();
    },
    upImgPath(el) {
      console.log(this.selectImgArr);
      switch (this.selectImgArr) {
        case "images":
          console.log(el.target);
          var file = el.target.files[0]; //name: "dangqi1.png" || type: "image/png"
          this.uploadImage.images = file;
          var filePath = this.getObjectURL(file);
          this.form.images = filePath;
          console.log(this.form);
          console.log(this.uploadImage);
          this.$refs.referenceUpload.value = null;
          break;
        case "optionimages":
          // formArr = this.optionlist[this.isoptionindex].file;
          // showArr = this.optionlist[this.isoptionindex].optionfile;
          console.log(el.target);
          file = el.target.files[0]; //name: "dangqi1.png" || type: "image/png"
          this.optionlist[this.isoptionindex].file = file;
          filePath = this.getObjectURL(file);
          console.log(filePath);
          this.optionlist[this.isoptionindex].optionfile = filePath;
          console.log(this.optionlist);
          this.$refs.referenceUpload.value = null;
          break;
      }
    },
    getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        // basic
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },
    //图片删除
    deleItem(name, index) {
      console.log(name, index);
      // if (!this.isedit) {
      //添加
      switch (name) {
        case "images":
          this.form.images = "";
          this.uploadImage.images = "";
          break;
        case "optionimages":
          this.optionlist[index].optionfile = "";
          this.optionlist[index].file = "";
          break;
      }

      // } else {
      //   //编辑
      //   switch (name) {
      //     case "images":
      //       formArr = this.uploadImage.images;
      //       showArr = this.form.images;
      //       imageListArr = this.imageList.images;
      //       break;
      //   }
      //   console.log(formArr);
      //   console.log(JSON.stringify(formArr[index]).indexOf(API_URL) > -1);
      //   if (JSON.stringify(formArr[index]).indexOf(API_URL) > -1) {
      //     this.deleImgArr.push(imageListArr[index]);
      //   }
      //   formArr.splice(index, 1);
      //   showArr.splice(index, 1);
      //   imageListArr.splice(index, 1);
      // }
    },

    addDomain1() {
      this.optionlist.push({
        optiontitle: "", //选项标题
        optiontype: 1, //类型
        subopitons: [
          {
            subopitonstitile: "", //子选项标题
            subopitonsnum: 0 //子选项被选择数
          }
        ] //子选项
      });
    },
    addDomain2() {
      this.optionlist.push({
        optiontitle: "", //选项标题
        optiontype: 2, //类型
        subopitonsitme: null, //选择次数
        mulopitons: [
          {
            subopitonstitile: "", //子选项标题
            subopitonsnum: 0 //子选项被选择数
          }
        ] //子选项
      });
    },
    addDomain3() {
      this.optionlist.push({
        optiontitle: "", //选项标题
        optiontype: 3 //类型
      });
    },
    addsub1(index) {
      this.optionlist[index].subopitons.push({
        subopitonstitile: "", //子选项标题
        subopitonsnum: 0 //子选项被选择数
      });
    },
    addsub2(index) {
      this.optionlist[index].mulopitons.push({
        subopitonstitile: "", //子选项标题
        subopitonsnum: 0 //子选项被选择数
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    removeDomain(item) {
      var index = this.optionlist.indexOf(item);
      if (index !== -1) {
        this.optionlist.splice(index, 1);
      }
    },

    removesub1(item, index) {
      var index1 = this.optionlist[index].subopitons.indexOf(item);
      console.log(index1);
      if (index !== -1) {
        this.optionlist[index].subopitons.splice(index1, 1);
      }
    },
    removesub2(item, index) {
      var index1 = this.optionlist[index].mulopitons.indexOf(item);
      console.log(index1);
      if (index !== -1) {
        this.optionlist[index].mulopitons.splice(index1, 1);
      }
    }
  }
};
</script>

<style lang="scss">
.Box {
  width: 1200px;
  margin: 0 auto;
  background-color: #ffffff;
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .titles {
    font-weight: 550;
    font-size: 20px;
  }
  .el-form {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
  }
  .dan {
    margin: 0 0 0 40px;
  }
  .updataImg {
    display: flex;
    .addImg {
      width: 100px;
      height: 100px;
      line-height: 90px;
      text-align: center;
      border: solid #ccc 1px;
      font-size: 60px;
      color: #ccc;
      cursor: pointer;
    }
  }
  .icon {
    position: absolute;
    top: 0;
    right: 0;
    background: rgba($color: #000000, $alpha: 0.5);
    color: #fff;
    padding: 5px;
  }
  .delectBox {
    position: relative;
  }
  .for_css {
    padding: 10px;
    width: 96%;
    border: 1px solid #ebeef5;
    border-radius: 5px;
  }
}
</style>
